package com.gzsxy.esjy.thread;


import com.gzsxy.esjy.configuration.properties.ServerProperties;
import com.gzsxy.esjy.pool.StandardThreadExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import java.util.concurrent.*;

/**
 * 业务线程池
 * @author zhangxiaolong
 * @date 2022/7/6 9:36
 */
public class NettyServicePool {

	private final static Logger log = LoggerFactory.getLogger(NettyServicePool.class) ;
	/**
	 * 线程池
	 */
	private ThreadPoolExecutor pool ;
	
	@Autowired
	private ServerProperties serverConfig ;

	//初始化创建线程池
	@PostConstruct
	private void intit() {
		//执行策略： 优先扩充线程到maxThread，再offer到queue，如果满了就reject
		//  *                           比较适合于业务处理需要远程资源的场景
		pool = new StandardThreadExecutor(serverConfig.getCoremumPoolSize(), serverConfig.getMaxmumPoolSize(), serverConfig.getLive(), TimeUnit.SECONDS,new RejectedExecutionHandler() {
			@Override
			public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
				log.info("server rejected to connect..");
			}
		});

	}
	
	/**
	 * 执行带有返回值的线程
	 * @param <T>
	 * @param task
	 * @return
	 */
	public <T> Future<T> startWidthResult(Callable<T> task){
		return pool.submit(task);
	}
	
	
	/**
	 * 执行无返回值的线程
	 * @param <T>
	 * @param task
	 * @return
	 */
	public void start(Runnable task){
		pool.execute(task);
	}
	
}
